package com.duoduo.service.impl;


import com.duoduo.dto.GoodsSalesDTO;
import com.duoduo.entity.Orders;
import com.duoduo.mapper.OrderMapper;
import com.duoduo.mapper.UserMapper;
import com.duoduo.service.ReportService;
import com.duoduo.service.WorkspaceService;
import com.duoduo.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计 begin 到 end 的营业额
     * -营业额为订单状态为已完成的订单金额
     * @param begin: 2022-10-15
     * @param end: 2022-10-22
     * @return TurnoverReportVO:
     *     //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
     *     private String dateList;
     *     //营业额，以逗号分隔，例如：406.0,1520.0,75.0
     *     private String turnoverList;
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 构建存放从 begin 到 end 每天的日期LocalDate 的集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);  // 日期加1
            dateList.add(begin);
        }

        // join 转为规定格式的字符串
        String dateListString = StringUtils.join(dateList, ",");// 2022-10-15,2022-10-16,2022-10-17

        // 遍历日期，查询每天对应的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 构造某天的时间范围
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);  // 2022-10-15 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);  // 2022-10-15 23:59:59

            // select sum(amount) from orders where order_time > ? and order_time < ? and status = 5;
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            // 如果当天没有数据turnover为null，要转为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        // 转为规定格式的字符串
        String turnoverListString = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();
    }


    /**
     * 统计指定时间段的用户数量
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        // 构建存放从begin到end的日期的集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天新增的用户数量
        List<Integer> newUserList = new ArrayList<>();
        // 存放每天的总用户数量
        List<Integer> totalUserList = new ArrayList<>();

        // 遍历日期，查询每天对应的用户数量
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN); 
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 统计某天的用户总数：select count(*) from user where create_time < ?
            HashMap<Object, Object> map = new HashMap<>();
            map.put("end",endTime);
            Integer totalUser =  userMapper.countByMap(map);

            // 统计某天的新增用户数量：select count(*) from user where create_time < ? and create_time > ?
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        // 封装为 UserReportVO 并返回
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 统计指定时间段内的订单数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 构建存放从begin到end的日期的集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 一段时间内的订单总数
        Integer totalOrderCount = 0;
        // 一段时间内的有效订单数量
        Integer validOrderCount = 0;
        // 每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        // 每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 统计订单数：select count(*) from orders where order_time < ? and order_time > ?
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer count = orderMapper.getCountByMap(map);
            count = count == null ? 0 : count;
            orderCountList.add(count);
            totalOrderCount += count;

            // 统计有效订单数：select count(*) from orders where order_time < ? and order_time > ? and status = ?
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.getCountByMap(map);
            validCount = validCount == null ? 0 : validCount;
            validOrderCountList.add(validCount);
            validOrderCount += validCount;
        }

        // 订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计指定时间段内的销量排名top10
     * -10个，降序
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10(LocalDate begin, LocalDate end) {
        // begin到end的LocalDateTime格式的时间段
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // select od.name,sum(od.number)
        // from order_detail od, orders o
        // where od.order_id = o.id and o.order_time > ? and o.order_time < ? and o.status = 5
        // group by od.name
        // order by sum(od.number) desc
        // limit 10
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        // 转为VO
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameListString = StringUtils.join(nameList, ",");

        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberListString = StringUtils.join(numberList, ",");

        return new SalesTop10ReportVO(nameListString, numberListString);
    }

    /**
     * 导出最近30天的营业数据为excel
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1. 查询数据库，获取最近30天的营业数据
        // 近30天的日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        // 查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX)
        );


        // 2. 通过POI写入到excel模板文件
        // 通过类加载器获取excel模板文件的输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);

            // 填充概览数据
            XSSFSheet sheet = excel.getSheet("sheet1");  // 获取sheet页

            sheet.getRow(1).getCell(1).setCellValue("时间: " + dateBegin + "至" + dateEnd);  // 填充时间段

            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());  // 填充营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());  // 填充订单完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());  // 填充新增用户数

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());  // 填充有效订单数量
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());  // 填充平均客单价

            // 填充每天的明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                // 填充
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
            }


            // 3. 通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            // 关闭资源
            outputStream.close();
            excel.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
